package com.etone.smartAudit.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.CertificateGroup;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.CertificateGroupMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 存证单群组信息  服务实现类
 * </p>
 *
 * @author jiayen
 * @since 2021-06-08
 */
@Service
public class CertificateGroupService extends ServiceImpl<CertificateGroupMapper, CertificateGroup> {

    /**
     * 添加群组
     *
     * @param admin
     * @param groupName
     */
    public void addGroup(Admin admin, String groupName, Integer type, Integer itemId) {
        //同一个项目下面群组名称不能重复
        //判断群组是否已经存在
        LambdaQueryWrapper<CertificateGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CertificateGroup::getItemId, itemId)
                .eq(CertificateGroup::getGroupName, groupName);
        List<CertificateGroup> groups = this.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(groups)) {
            throw new CustomParameterizedException("该项目下已经存在该群组!");
        }

        CertificateGroup group = new CertificateGroup();
        group.setGroupName(groupName);
        group.setCreateBy(admin.getId());
        group.setType(type);
        group.setCreateTime(LocalDateTime.now());
        group.setUpdateTime(LocalDateTime.now());
        group.setItemId(itemId);
        this.save(group);
    }


    /***
     * 获取群组列表
     * @return
     */
    public List<CertificateGroup> getGroupList(Integer type, Integer itemId) {
        LambdaQueryWrapper<CertificateGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CertificateGroup::getType, type);
        if (itemId != null && itemId > 0) {
            queryWrapper.eq(CertificateGroup::getItemId, itemId);
        }
        return this.list(queryWrapper);
    }
}
